<?php

namespace july\julyadmin\builder\traits\actions;

/**
 * 禁用/启用
 */

trait HasDisabled
{
    public function disabled()
    {
        $info = input('post.');
        if (!isset($info[$this->getPk()]) || !$info[$this->getPk()]) {
            $this->error('主键信息不能为空！');
        }
        $pk  = trim($info[$this->getPk()]);
        $pks = explode(",", $pk);

        foreach ($pks as $k => $v) {
            if (isset($this->noDisabledPrimarykeys) && in_array($v, $this->noDisabledPrimarykeys)) {
                $this->error('当前数据不允许操作！');
            }
        }

        foreach ($pks as $k => $v) {
            $find = $this->dataModel->where($this->getPk(), $v)->find();
            if (!$find) {
                $this->error('要操作的数据不存在！');
            }

            $data = [$this->disabledField => $find->disabled ? 0 : 1];
            $res  = $this->dataModel->where($this->getPk(), "in", $v)->save($data);
            if (!$res) {
                $this->error('操作失败！');
            }
        }
        $this->success('操作成功！');
    }
}
